import sys
import pyautogui
import time
import keyboard as kb
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout,
                             QPushButton, QListWidget, QDialog, QMessageBox,
                             QFileDialog, QGroupBox, QSizePolicy, QLabel)
from PyQt5.QtCore import QThread, pyqtSignal, pyqtSlot
import json
from pynput import mouse, keyboard
import os
from datetime import datetime
import pydirectinput
from components.mousemovedialog import MouseMoveDialog
from components.mouseclickdialog import MouseClickDialog
from components.mousebuttondialog import MouseButtonDialog
from components.mousescrolldialog import MouseScrollDialog
from components.keyboardtypedialog import KeyboardTypeDialog
from components.hotkeydialog import HotkeyDialog
from components.delaydialog import DelayDialog
from components.whileloopdialog import WhileLoopDialog
from components.imagelocatedialog import ImageLocateDialog
from components.screenshotdialog import ScreenshotDialog
from components.specialkeydialog import SpecialKeyDialog
from core.menubar import MenuBar
from core.mainwindow import MainWindow
from core.ApiServer import set_main_window, start_server
import threading


class ScriptRunner(QThread):
    finished = pyqtSignal()
    error = pyqtSignal(str)
    log_message = pyqtSignal(str)

    def __init__(self, actions):
        super().__init__()
        self.actions = actions
        self._is_running = True
        self.exit_flag = False
        self.log_message.connect(self.save_log)

    def log(self, message):
        """发送日志消息"""
        timestamp = time.strftime("%H:%M:%S", time.localtime())
        full_message = f"[log {timestamp}] {message}]"
        self.log_message.emit(full_message)
        print(full_message)

    def save_log(self, msg):
        try:
            log_dir = "logs"
            os.makedirs(log_dir, exist_ok=True)

            current_date = datetime.now().strftime("%Y-%m-%d")
            log_file = os.path.join(log_dir, f"{current_date}.log")

            with open(log_file, 'a', encoding='utf-8') as f:
                timestamp = datetime.now().strftime("%H:%M:%S")
                f.write(f"[{timestamp}] {msg}\n")

        except Exception as e:
            print(f"保存日志失败: {str(e)}")

    def on_press(self, key):
        try:
            if key.char == self.current_exit_key:
                self.exit_flag = True
        except AttributeError:
            if key == keyboard.Key.esc and self.current_exit_key == 'esc':
                self.exit_flag = True

    def run(self):
        try:
            i = 0
            while i < len(self.actions) and self._is_running:
                action = self.actions[i]
                print(action["type"])
                if action["type"] == "get_resolution":
                    size = pyautogui.size()
                    self.log(f"屏幕分辨率: {size.width}x{size.height}")
                    print(f"屏幕分辨率: {size.width}x{size.height}")

                elif action["type"] == "get_position":
                    pos = pyautogui.position()
                    print(f"当前鼠标位置: {pos.x}, {pos.y}")
                    self.log(f"当前鼠标位置: {pos.x}, {pos.y}")

                elif action["type"] == "moveTo":
                    pyautogui.moveTo(action["x"], action["y"], duration=action["duration"])
                    self.log(f"移动鼠标到 ({action['x']}, {action['y']})，耗时 {action['duration']}秒")

                elif action["type"] == "move":
                    pyautogui.move(action["x"], action["y"], duration=action["duration"])
                    self.log(f"相对移动 ({action['x']}, {action['y']})，耗时 {action['duration']}秒")

                elif action["type"] == "down":
                    pyautogui.mouseDown(button=action["button"])
                    self.log(f"鼠标 {action['button']} 键按下")

                elif action["type"] == "up":
                    pyautogui.mouseUp(button=action["button"])
                    self.log(f"鼠标 {action['button']} 键抬起")

                elif action["type"] == "click":
                    pyautogui.click(button=action["button"], clicks=action["clicks"])
                    self.log(f"鼠标 {action['button']} 键点击 {action['clicks']} 次")

                elif action["type"] == "dblclick":
                    pyautogui.doubleClick(button=action["button"])
                    self.log(f"鼠标 {action['button']} 键双击")

                elif action["type"] == "scroll":
                    if action["x"] is not None or action["y"] is not None:
                        current_x, current_y = pyautogui.position()
                        new_x = action["x"] if action["x"] is not None else current_x
                        new_y = action["y"] if action["y"] is not None else current_y
                        self.log(f"移动鼠标到 ({new_x}, {new_y}) 并滚动 {action['amount']} 单位")
                        pyautogui.moveTo(new_x, new_y)
                    else:
                        self.log(f"滚动 {action['amount']} 单位")
                    pyautogui.scroll(action["amount"])

                elif action["type"] == "typewrite":
                    pyautogui.typewrite(action["text"], interval=action["interval"])
                    self.log(f"键盘输入: '{action['text']}' (间隔: {action['interval']}秒)")

                elif action["type"] == "hotkey":
                    self.log(f"组合按键: {'+'.join(action['keys'])}")
                    pyautogui.hotkey(*action["keys"])

                elif action["type"] == "delay":
                    end_time = time.time() + action["seconds"]
                    self.log(f"延时 {action['seconds']} 秒")
                    while time.time() < end_time and self._is_running:
                        time.sleep(0.1)

                elif action["type"] == "while":
                    exit_key = action["exit_key"]
                    self.current_exit_key = action["exit_key"].lower()
                    self.log(f"开始循环执行 (按 {exit_key} 退出)")

                    # 启动监听器
                    self.listener = keyboard.Listener(on_press=self.on_press)
                    self.listener.start()

                    while not kb.is_pressed(exit_key) and self._is_running and not self.exit_flag:
                        j = i + 1
                        while j < len(self.actions) and self.actions[j].get("type") != "endwhile" and self._is_running:
                            inner_action = self.actions[j]

                            if inner_action["type"] == "move":
                                pyautogui.move(inner_action["x"], inner_action["y"],
                                               duration=inner_action["duration"])
                            elif inner_action["type"] == "moveTo":
                                pyautogui.moveTo(inner_action["x"], inner_action["y"],
                                                 duration=inner_action["duration"])
                            elif inner_action["type"] == "down":
                                pyautogui.mouseDown(button=inner_action["button"])
                            elif inner_action["type"] == "up":
                                pyautogui.mouseUp(button=inner_action["button"])
                            elif inner_action["type"] == "click":
                                pyautogui.click(button=inner_action["button"], clicks=inner_action["clicks"])
                            elif inner_action["type"] == "dblclick":
                                pyautogui.doubleClick(button=inner_action["button"])
                            elif inner_action["type"] == "scroll":
                                if inner_action["x"] is not None or inner_action["y"] is not None:
                                    current_x, current_y = pyautogui.position()
                                    new_x = inner_action["x"] if inner_action["x"] is not None else current_x
                                    new_y = inner_action["y"] if inner_action["y"] is not None else current_y
                                    pyautogui.moveTo(new_x, new_y)
                                pyautogui.scroll(inner_action["amount"])
                            elif inner_action["type"] == "typewrite":
                                pyautogui.typewrite(inner_action["text"], interval=inner_action["interval"])
                            elif inner_action["type"] == "hotkey":
                                pyautogui.hotkey(*inner_action["keys"])
                            elif inner_action["type"] == "delay":
                                end_time_inner = time.time() + inner_action["seconds"]
                                while time.time() < end_time_inner and self._is_running:
                                    time.sleep(0.1)
                            elif inner_action["type"] == "image_locate":
                                try:
                                    location = pyautogui.locateOnScreen(inner_action['image_path'], grayscale=True,
                                                                        confidence=inner_action['confidence'])
                                    time.sleep(0.5)
                                    if location is not None:
                                        center = pyautogui.center(location)
                                        if action["click"]:
                                            if action["click_type"] == "double":
                                                pyautogui.doubleClick(center.x, center.y)
                                            else:
                                                pyautogui.click(center.x, center.y)
                                except Exception as e:
                                    print(e)
                            elif inner_action["type"] == "specialkey":
                                pydirectinput.press(inner_action["text"])
                                #pyautogui.press(inner_action["text"])
                                self.log(f"按下特殊键: {inner_action['text']}")

                            j += 1
                        time.sleep(0.01)
                    self.listener.stop()

                    i = j if j < len(self.actions) else i

                elif action["type"] == "screenshot":
                    pyautogui.screenshot(action["filename"])

                elif action["type"] == "image_locate":
                    try:
                        location = pyautogui.locateOnScreen(
                            action["image_path"],
                            grayscale=True,
                            confidence=action["confidence"]
                        )
                        time.sleep(0.5)
                        if location is not None:
                            center = pyautogui.center(location)
                            print(f"找到图片 '{action['image_path']}' 在位置: {center}")

                            if action["click"]:
                                if action["click_type"] == "double":
                                    pyautogui.doubleClick(center.x, center.y)
                                else:
                                    pyautogui.click(center.x, center.y)
                        else:
                            print(f"未找到图片 '{action['image_path']}'")

                    except Exception as e:
                        print(f"图片定位出错: {str(e)}")

                elif action["type"] == "specialkey":
                    # pyautogui.press(action["text"])
                    pydirectinput.press(action["text"])
                    self.log(f"按下特殊键: {action['text']}")
                i += 1

            self.finished.emit()

        except Exception as e:
            self.error.emit(str(e))


class AutoGUIScriptBuilder(MainWindow):
    # 创建自定义信号用于HTTP调用
    run_script_http = pyqtSignal(list)

    def __init__(self):
        super().__init__()
        self.setGeometry(100, 100, 800, 600)

        menubar = MenuBar(self)
        self.setMenuWidget(menubar)
        self.setWindowIcon(QIcon("pic/app.ico"))

        self.actions = []
        self.script_thread = None

        # 连接信号到槽函数
        self.run_script_http.connect(self.run_script_from_http)

        self.create_widgets()

        # 启动监听线程
        self.listener_thread = threading.Thread(
            target=self.start_mouse_listener,
            daemon=True
        )

        self.listener_thread.start()

        # 设置主窗口引用
        set_main_window(self)

        # 启动FastAPI服务器线程
        self.api_thread = threading.Thread(
            target=start_server,
            daemon=True
        )
        self.api_thread.start()

    @pyqtSlot(list)
    def run_script_from_http(self, actions):
        """从HTTP请求运行脚本"""
        print(f"[HTTP] 接收到脚本执行请求，动作数量：{len(actions)}")
        self.actions = actions
        self.run_script(skip_confirmation=True)

    @pyqtSlot(dict)
    def add_action_from_http(self, action):
        """从HTTP请求添加动作"""
        if action:
            self.actions.append(action)
            self.update_script_list()

    def start_mouse_listener(self):
        with mouse.Listener(
                on_move=self.on_move,
        ) as listener:
            listener.join()

    def on_move(self, x, y):
        self.coordinates_label.setText(f"鼠标位置: ({x}, {y})")

    def save_project(self):
        """保存当前项目到JSON文件"""
        if not self.actions:
            QMessageBox.warning(self, "警告", "没有可保存的项目内容")
            return

        filename, _ = QFileDialog.getSaveFileName(
            self, "保存项目", "", "JSON 文件 (*.json);;所有文件 (*)")

        if not filename:
            return

        try:
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(self.actions, f, indent=4, ensure_ascii=False)
            QMessageBox.information(self, "成功", f"项目已保存到: {filename}")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"保存项目失败: {str(e)}")

    def load_project(self):
        """从JSON文件加载项目"""
        filename, _ = QFileDialog.getOpenFileName(
            self, "加载项目", "", "JSON 文件 (*.json);;所有文件 (*)")

        if not filename:
            return

        try:
            with open(filename, 'r', encoding='utf-8') as f:
                self.actions = json.load(f)
            self.update_script_list()
            QMessageBox.information(self, "成功", f"项目已从 {filename} 加载")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载项目失败: {str(e)}")

    def create_widgets(self):
        # 主窗口
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        # 主布局
        main_layout = QVBoxLayout(central_widget)

        # 左侧组件面板
        component_group = QGroupBox("可用组件")
        component_layout = QVBoxLayout()

        # 组件按钮
        buttons = [
            # ("获取屏幕分辨率", self.add_get_resolution),
            # ("获取鼠标位置", self.add_get_mouse_position),
            ("鼠标移动", self.add_mouse_move),
            ("鼠标按下", lambda: self.add_mouse_button("down")),
            ("鼠标抬起", lambda: self.add_mouse_button("up")),
            ("鼠标点击", self.add_mouse_click),
            ("鼠标双击", lambda: self.add_mouse_button("dblclick")),
            ("中键滚动", self.add_mouse_scroll),
            ("键盘输入", self.add_keyboard_type),
            ("特殊按键", self.add_special_key),
            ("组合按键", self.add_hotkey),
            ("延时", self.add_delay),
            ("循环执行", self.add_while_loop),
            ("图片定位点击", self.add_image_locate),
            ("保存截图", self.add_screenshot)
        ]

        for text, callback in buttons:
            button = QPushButton(text)
            button.clicked.connect(callback)
            button.setSizePolicy(QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Expanding))
            component_layout.addWidget(button)

        component_group.setLayout(component_layout)

        script_group = QGroupBox("脚本动作")
        script_layout = QVBoxLayout()

        self.script_list = QListWidget()
        self.script_list.itemDoubleClicked.connect(self.edit_action)
        script_layout.addWidget(self.script_list)

        # 脚本操作按钮
        button_layout = QHBoxLayout()

        buttons = [
            ("上移", self.move_up),
            ("下移", self.move_down),
            ("删除", self.delete_action),
            ("清空", self.clear_script)
        ]

        for text, callback in buttons:
            button = QPushButton(text)
            button.clicked.connect(callback)
            button_layout.addWidget(button)

        script_layout.addLayout(button_layout)
        script_group.setLayout(script_layout)

        # 底部按钮面板
        bottom_layout = QHBoxLayout()

        buttons = [
            ("运行脚本", self.run_script),
            ("保存脚本", self.save_script),
            ("保存项目", self.save_project),
            ("加载项目", self.load_project)
        ]

        for text, callback in buttons:
            button = QPushButton(text)
            button.clicked.connect(callback)
            bottom_layout.addWidget(button)

        vlayout = QHBoxLayout()

        vlayout.addWidget(component_group, stretch=1)
        vlayout.addWidget(script_group, stretch=3)

        main_layout.addLayout(bottom_layout)
        main_layout.addLayout(vlayout)

        self.coordinates_label = QLabel()
        self.log_message = QLabel()

        sts_lay = QHBoxLayout()
        sts_lay.addWidget(self.coordinates_label)
        sts_lay.addStretch()
        sts_lay.addWidget(self.log_message)

        main_layout.addLayout(sts_lay)

    def add_special_key(self):
        dialog = SpecialKeyDialog()
        if dialog.exec_() == QDialog.Accepted:
            action = dialog.get_action()
            if action:
                self.actions.append(action)
                self.update_script_list()

    # def add_get_resolution(self):
    #     action = {"type": "get_resolution", "desc": "获取屏幕分辨率"}
    #     self.actions.append(action)
    #     self.update_script_list()

    def add_image_locate(self):
        dialog = ImageLocateDialog()
        if dialog.exec_() == QDialog.Accepted:
            self.actions.append(dialog.get_action())
            self.update_script_list()

    # def add_get_mouse_position(self):
    #     action = {"type": "get_position", "desc": "获取鼠标当前位置"}
    #     self.actions.append(action)
    #     self.update_script_list()

    def add_mouse_move(self):
        dialog = MouseMoveDialog()
        if dialog.exec_() == QDialog.Accepted:
            self.actions.append(dialog.get_action())
            self.update_script_list()

    def add_mouse_button(self, button_type):
        dialog = MouseButtonDialog(button_type)
        if dialog.exec_() == QDialog.Accepted:
            self.actions.append(dialog.get_action())
            self.update_script_list()

    def add_mouse_click(self):
        dialog = MouseClickDialog()
        if dialog.exec_() == QDialog.Accepted:
            self.actions.append(dialog.get_action())
            self.update_script_list()

    #中键滚动
    def add_mouse_scroll(self):
        dialog = MouseScrollDialog()
        if dialog.exec_() == QDialog.Accepted:
            self.actions.append(dialog.get_action())
            self.update_script_list()

    def add_keyboard_type(self):
        dialog = KeyboardTypeDialog()
        if dialog.exec_() == QDialog.Accepted:
            self.actions.append(dialog.get_action())
            self.update_script_list()

    def add_hotkey(self):
        dialog = HotkeyDialog()
        if dialog.exec_() == QDialog.Accepted:
            self.actions.append(dialog.get_action())
            self.update_script_list()

    def add_delay(self):
        dialog = DelayDialog()
        if dialog.exec_() == QDialog.Accepted:
            self.actions.append(dialog.get_action())
            self.update_script_list()

    def add_while_loop(self):
        dialog = WhileLoopDialog()
        if dialog.exec_() == QDialog.Accepted:
            self.actions.append(dialog.get_action())
            self.update_script_list()

    def add_screenshot(self):
        dialog = ScreenshotDialog()
        dialog.exec_()

    def update_script_list(self):
        self.script_list.clear()
        for i, action in enumerate(self.actions, 1):
            self.script_list.addItem(f"{i}. {action['desc']}")

    def move_up(self):
        current_row = self.script_list.currentRow()
        if current_row > 0:
            self.actions[current_row], self.actions[current_row - 1] = self.actions[current_row - 1], self.actions[
                current_row]
            self.update_script_list()
            self.script_list.setCurrentRow(current_row - 1)

    def move_down(self):
        current_row = self.script_list.currentRow()
        if current_row < len(self.actions) - 1:
            self.actions[current_row], self.actions[current_row + 1] = self.actions[current_row + 1], self.actions[
                current_row]
            self.update_script_list()
            self.script_list.setCurrentRow(current_row + 1)

    def delete_action(self):
        current_row = self.script_list.currentRow()
        if current_row >= 0:
            del self.actions[current_row]
            self.update_script_list()

    def clear_script(self):
        self.actions = []
        self.update_script_list()

    def edit_action(self, item):
        row = self.script_list.row(item)
        action = self.actions[row]

        dialog = None
        if action["type"] == "move":
            dialog = MouseMoveDialog(action, self)
        if action["type"] == "moveTo":
            dialog = MouseMoveDialog(action, self)
        elif action["type"] in ["down", "up", "dblclick"]:
            dialog = MouseButtonDialog(action["type"], action, self)
        elif action["type"] == "click":
            dialog = MouseClickDialog(action, self)
        elif action["type"] == "scroll":
            dialog = MouseScrollDialog(action, self)
        elif action["type"] == "typewrite":
            dialog = KeyboardTypeDialog(action, self)
        elif action["type"] == "hotkey":
            dialog = HotkeyDialog(action, self)
        elif action["type"] == "delay":
            dialog = DelayDialog(action, self)
        elif action["type"] == "while":
            dialog = WhileLoopDialog(action, self)
        elif action["type"] == "image_locate":
            dialog = ImageLocateDialog(action, self)
        elif action["type"] == "specialkey":
            dialog = SpecialKeyDialog(action, self)

        if dialog and dialog.exec_() == QDialog.Accepted:
            self.actions[row] = dialog.get_action()
            self.update_script_list()

    def run_script(self, skip_confirmation=False):
        # 检查动作列表是否有效
        if not self.actions or not isinstance(self.actions, list):
            print("错误：无效的动作列表")
            if not skip_confirmation:
                QMessageBox.warning(self, "警告", "没有可运行的脚本动作")
            return

        # 如果已有线程在运行，先停止
        if self.script_thread and self.script_thread.isRunning():
            self.script_thread.stop()
            self.script_thread.wait()

        # 询问是否继续
        if not skip_confirmation:
            reply = QMessageBox.question(self, "确认",
                                         "即将运行脚本，请确保鼠标键盘控制权已准备好。继续吗？",
                                         QMessageBox.Yes | QMessageBox.No)
            if reply != QMessageBox.Yes:
                return

        # 创建并启动脚本线程
        self.script_thread = ScriptRunner(self.actions)
        self.script_thread.finished.connect(self.on_script_finished)
        self.script_thread.error.connect(self.on_script_error)
        self.script_thread.start()

        self.script_thread.log_message.connect(self.on_script_log_message)
        # 禁用运行按钮，避免重复执行
        for widget in self.findChildren(QPushButton):
            if widget.text() == "运行脚本":
                widget.setEnabled(False)

    def on_script_log_message(self, msg):
        self.log_message.setText(msg)

    def on_script_finished(self):
        QMessageBox.information(self, "完成", "脚本执行完成")
        self.enable_run_button()

    def on_script_error(self, error_msg):
        QMessageBox.critical(self, "错误", f"脚本执行出错: {error_msg}")
        self.enable_run_button()

    def enable_run_button(self):
        for widget in self.findChildren(QPushButton):
            if widget.text() == "运行脚本":
                widget.setEnabled(True)

    def closeEvent(self, event):
        # 窗口关闭时停止脚本线程
        if self.http_thread.isRunning():
            self.http_thread.stop()
            self.http_thread.wait()
        if self.script_thread and self.script_thread.isRunning():
            self.script_thread.stop()
            self.script_thread.wait()
        event.accept()

    def save_script(self):
        if not self.actions:
            QMessageBox.warning(self, "警告", "没有可保存的脚本动作")
            return

        filename, _ = QFileDialog.getSaveFileName(
            self, "保存脚本", "", "Python 文件 (*.py);;所有文件 (*)")

        if not filename:
            return

        try:
            with open(filename, "w", encoding="utf-8") as f:
                f.write("import pyautogui\nimport time\nimport keyboard as kb\n\n")
                f.write("# 自动化脚本 - 由 PyAutoGUI 脚本生成器创建\n\n")

                i = 0
                while i < len(self.actions):
                    action = self.actions[i]
                    print(action["type"])
                    if action["type"] == "get_resolution":
                        f.write("# 获取屏幕分辨率\n")
                        f.write("size = pyautogui.size()\n")
                        f.write('print(f"屏幕分辨率: {size.width}x{size.height}")\n\n')

                    elif action["type"] == "get_position":
                        f.write("# 获取鼠标位置\n")
                        f.write("pos = pyautogui.position()\n")
                        f.write('print(f"当前鼠标位置: {pos.x}, {pos.y}")\n\n')

                    elif action["type"] == "moveTo":
                        f.write(f"# 绝对移动到 ({action['x']}, {action['y']})\n")
                        f.write(f"pyautogui.moveTo({action['x']}, {action['y']}, duration={action['duration']})\n\n")

                    elif action["type"] == "move":
                        f.write(f"# 相对移动 ({action['x']}, {action['y']})\n")
                        f.write(f"pyautogui.move({action['x']}, {action['y']}, duration={action['duration']})\n\n")

                    elif action["type"] == "down":
                        f.write(f"# 鼠标 {action['button']} 键按下\n")
                        f.write(f"pyautogui.mouseDown(button='{action['button']}')\n\n")

                    elif action["type"] == "up":
                        f.write(f"# 鼠标 {action['button']} 键抬起\n")
                        f.write(f"pyautogui.mouseUp(button='{action['button']}')\n\n")

                    elif action["type"] == "click":
                        f.write(f"# 鼠标 {action['button']} 键点击 {action['clicks']} 次\n")
                        f.write(f"pyautogui.click(button='{action['button']}', clicks={action['clicks']})\n\n")

                    elif action["type"] == "dblclick":
                        f.write(f"# 鼠标 {action['button']} 键双击\n")
                        f.write(f"pyautogui.doubleClick(button='{action['button']}')\n\n")

                    elif action["type"] == "scroll":
                        desc = f"# 鼠标滚轮滚动 {action['amount']} 单位"
                        if action["x"] is not None and action["y"] is not None:
                            f.write(f"{desc} (在位置 {action['x']}, {action['y']})\n")
                            f.write(f"pyautogui.scroll({action['amount']}, x={action['x']}, y={action['y']})\n\n")
                        elif action["x"] is not None:
                            f.write(f"{desc} (在X位置 {action['x']})\n")
                            f.write(f"pyautogui.scroll({action['amount']}, x={action['x']})\n\n")
                        elif action["y"] is not None:
                            f.write(f"{desc} (在Y位置 {action['y']})\n")
                            f.write(f"pyautogui.scroll({action['amount']}, y={action['y']})\n\n")
                        else:
                            f.write(f"{desc}\n")
                            f.write(f"pyautogui.scroll({action['amount']})\n\n")

                    elif action["type"] == "typewrite":
                        f.write(f"# 键盘输入: '{action['text']}'\n")
                        f.write(f"pyautogui.typewrite('{action['text']}', interval={action['interval']})\n\n")

                    elif action["type"] == "specialkey":
                        f.write(f"# 键盘输入: '{action['text']}'\n")
                        f.write(f"pydirectinput.press('{action['text']}')\n\n")

                    elif action["type"] == "hotkey":
                        f.write(f"# 组合按键: {'+'.join(action['keys'])}\n")
                        keys_str = ", ".join(f"'{key}'" for key in action["keys"])
                        f.write(f"pyautogui.hotkey({keys_str})\n\n")

                    elif action["type"] == "delay":
                        f.write(f"# 延时 {action['seconds']} 秒\n")
                        f.write(f"time.sleep({action['seconds']})\n\n")

                    elif action["type"] == "while":
                        exit_key = action["exit_key"]
                        f.write(f"# 循环执行 (按 {exit_key} 退出)\n")
                        f.write(f"while not kb.is_pressed('{exit_key}'):\n")

                        j = i + 1
                        while j < len(self.actions) and self.actions[j].get("type") != "endwhile":
                            inner_action = self.actions[j]

                            if inner_action["type"] == "move":
                                f.write(
                                    f"    pyautogui.move({inner_action['x']}, {inner_action['y']}, duration={inner_action['duration']})\n")

                            elif inner_action["type"] == "moveTo":
                                f.write(
                                    f"    pyautogui.moveTo({inner_action['x']}, {inner_action['y']}, duration={inner_action['duration']})\n")

                            elif inner_action["type"] == "down":
                                f.write(f"    pyautogui.mouseDown(button='{inner_action['button']}')\n")

                            elif inner_action["type"] == "up":
                                f.write(f"    pyautogui.mouseUp(button='{inner_action['button']}')\n")

                            elif inner_action["type"] == "click":
                                f.write(
                                    f"    pyautogui.click(button='{inner_action['button']}', clicks={inner_action['clicks']})\n")

                            elif inner_action["type"] == "dblclick":
                                f.write(f"    pyautogui.doubleClick(button='{inner_action['button']}')\n")

                            elif inner_action["type"] == "scroll":
                                if inner_action["x"] is not None and inner_action["y"] is not None:
                                    f.write(
                                        f"    pyautogui.scroll({inner_action['amount']}, x={inner_action['x']}, y={inner_action['y']})\n")
                                elif inner_action["x"] is not None:
                                    f.write(f"    pyautogui.scroll({inner_action['amount']}, x={inner_action['x']})\n")
                                elif inner_action["y"] is not None:
                                    f.write(f"    pyautogui.scroll({inner_action['amount']}, y={inner_action['y']})\n")
                                else:
                                    f.write(f"    pyautogui.scroll({inner_action['amount']})\n")

                            elif inner_action["type"] == "typewrite":
                                f.write(
                                    f"    pyautogui.typewrite('{inner_action['text']}', interval={inner_action['interval']})\n")
                            elif inner_action["type"] == "specialkey":
                                f.write(
                                    f"    pydirectinput.press('{inner_action['text']}')\n")
                            elif inner_action["type"] == "hotkey":
                                keys_str = ", ".join(f"'{key}'" for key in inner_action["keys"])
                                f.write(f"    pyautogui.hotkey({keys_str})\n")

                            elif inner_action["type"] == "delay":
                                f.write(f"    time.sleep({inner_action['seconds']})\n")

                            elif action["type"] == "image_locate":
                                f.write(f"# 定位图片 '{action['image_path']}' (置信度: {action['confidence']})\n")
                                f.write(
                                    f"    location = pyautogui.locateOnScreen('{action['image_path']}',  grayscale=True, confidence={action['confidence']})\n")
                                f.write("    if location is not None:\n")
                                f.write("    center = pyautogui.center(location)\n")
                                if action["click"]:
                                    if action["click_type"] == "double":
                                        f.write("    pyautogui.doubleClick(center.x,center.y)\n")
                                    else:
                                        f.write("    pyautogui.click(center.x,center.y)\n")
                                f.write("\n")
                            j += 1

                        f.write("\n")
                        i = j

                    elif action["type"] == "screenshot":
                        f.write(f"# 保存截图到: {action['filename']}\n")
                        f.write(f"pyautogui.screenshot('{action['filename']}')\n\n")

                    elif action["type"] == "image_locate":
                        f.write(f"# 定位图片 '{action['image_path']}' (置信度: {action['confidence']})\n")
                        f.write(
                            f"location = pyautogui.locateOnScreen('{action['image_path']}',   grayscale=True,confidence={action['confidence']})\n")
                        f.write("if location is not None:\n")
                        f.write("    center = pyautogui.center(location)\n")
                        if action["click"]:
                            if action["click_type"] == "double":
                                f.write("    pyautogui.doubleClick(center.x,center.y)\n")
                            else:
                                f.write("    pyautogui.click(center.x,center.y)\n")
                        f.write("\n")

                    i += 1

            QMessageBox.information(self, "成功", f"脚本已保存到: {filename}")

        except Exception as e:
            QMessageBox.critical(self, "错误", f"保存脚本失败: {str(e)}")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = AutoGUIScriptBuilder()
    window.show()
    sys.exit(app.exec_())
